<?php
session_start();

// 启用错误显示
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 检查用户是否已登录
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// 导入数据库连接
require_once 'database.php';

// 检查用户权限
$user_id = $_SESSION['user_id'];
$sql = "SELECT role FROM user_roles WHERE user_id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user_role = $result->fetch_assoc();

if (!$user_role || $user_role['role'] !== '考试项目管理员') {
    echo "<script>alert('权限不足，仅考试项目管理员可以访问此页面。'); window.history.back();</script>";
    exit();
}

// 获取传入的考试项目ID
$exam_id = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : 0;
if ($exam_id <= 0) {
    echo "<script>alert('无效的考试项目ID。'); window.history.back();</script>";
    exit();
}

// 获取考试项目信息
$sql = "SELECT exam_name FROM exams WHERE id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$result = $stmt->get_result();
$exam_info = $result->fetch_assoc();

if (!$exam_info) {
    echo "<script>alert('未找到指定的考试项目。'); window.history.back();</script>";
    exit();
}

// 处理AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    if ($_POST['action'] === 'calculate_data') {
        // 获取里程碑1的数据
        $sql = "SELECT * FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ? ORDER BY session_number";
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param("i", $exam_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $sessions = $result->fetch_all(MYSQLI_ASSOC);
        
        if (empty($sessions)) {
            echo json_encode(['success' => false, 'message' => '请先完成里程碑1的数据填写']);
            exit();
        }
        
        $calculations = [];
        
        // 1. 计算考试项目需要的考场总数（不含备用考场）
        $max_rooms_needed = 0;
        foreach ($sessions as $session) {
            $rooms_needed = intval($session['rooms_needed_without_backup']);
            if ($rooms_needed > $max_rooms_needed) {
                $max_rooms_needed = $rooms_needed;
            }
        }
        $calculations['project_total_rooms'] = $max_rooms_needed;
        
        // 2. 计算每场次需要监考员总数（不含备用考场）
        $session_invigilator_counts = [];
        foreach ($sessions as $session) {
            $rooms_needed = intval($session['rooms_needed_without_backup']);
            $invigilators_per_room = intval($session['invigilators_per_room']);
            $session_total = $rooms_needed * $invigilators_per_room;
            $session_invigilator_counts[] = $session_total;
        }
        $calculations['session_invigilator_counts'] = $session_invigilator_counts;
        
        // 3. 计算考试项目需要监考员总数（含备用考场）
        $max_invigilators_needed = max($session_invigilator_counts);
        $backup_rooms = 0;
        foreach ($sessions as $session) {
            $backup_count = intval($session['backup_rooms_count']);
            if ($backup_count > $backup_rooms) {
                $backup_rooms = $backup_count;
            }
        }
        $project_total_invigilators = $max_invigilators_needed + ($backup_rooms * 2);
        $calculations['project_total_invigilators'] = $project_total_invigilators;
        
        // 更新数据库中的计算结果
        foreach ($sessions as $index => $session) {
            $session_id = $session['id'];
            $session_invigilators = $session_invigilator_counts[$index];
            
            $update_sql = "UPDATE arrange_examination_rooms_and_invigilators SET 
                          session_invigilators_total = ?,
                          project_total_rooms = ?,
                          project_total_invigilators = ?
                          WHERE id = ?";
            $update_stmt = $mysqli->prepare($update_sql);
            $update_stmt->bind_param("iiii", $session_invigilators, $max_rooms_needed, $project_total_invigilators, $session_id);
            $update_stmt->execute();
        }
        
        echo json_encode(['success' => true, 'calculations' => $calculations]);
        exit();
    }
}

// 获取现有数据
$sql = "SELECT * FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ? ORDER BY session_number";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$result = $stmt->get_result();
$existing_data = $result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编排考场及预编排监考员 - 里程碑2</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .milestone-nav {
            background-color: #f8f9fa;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        .milestone-nav .nav-link {
            color: #6c757d;
        }
        .milestone-nav .nav-link.active {
            background-color: #007bff;
            color: white;
        }
        .calculation-result {
            background-color: #e9ecef;
            padding: 15px;
            border-radius: 5px;
            margin: 10px 0;
        }
        .session-detail {
            border: 1px solid #dee2e6;
            padding: 10px;
            margin: 5px 0;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <?php include_once 'common/navigation.php'; ?>
    
    <div class="container mt-4">
        <h2>编排考场及预编排监考员</h2>
        <h4>考试项目：<?php echo htmlspecialchars($exam_info['exam_name']); ?></h4>
        
        <!-- 里程碑导航 -->
        <div class="milestone-nav">
            <ul class="nav nav-pills">
                <li class="nav-item">
                    <a class="nav-link" href="arrange_examination_rooms_milestone1.php?exam_id=<?php echo $exam_id; ?>">里程碑1: 填写考场数据</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link active" href="#">里程碑2: 计算重要数据</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="arrange_examination_rooms_milestone3.php?exam_id=<?php echo $exam_id; ?>">里程碑3: 遴选课室</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="arrange_examination_rooms_milestone4.php?exam_id=<?php echo $exam_id; ?>">里程碑4: 编排考场号</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="arrange_examination_rooms_milestone5.php?exam_id=<?php echo $exam_id; ?>">里程碑5: 预编排监考员</a>
                </li>
            </ul>
        </div>
        
        <?php if (empty($existing_data)): ?>
            <div class="alert alert-warning">
                <h5>提示</h5>
                <p>请先完成里程碑1的数据填写，然后再进行计算。</p>
                <a href="arrange_examination_rooms_milestone1.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">返回里程碑1</a>
            </div>
        <?php else: ?>
            <!-- 当前数据展示 -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>当前考试场次数据</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>考试场次</th>
                                    <th>科目名称</th>
                                    <th>考试日期</th>
                                    <th>开始时间</th>
                                    <th>结束时间</th>
                                    <th>考场类型</th>
                                    <th>所需考场数（不含备用）</th>
                                    <th>每考场考生数</th>
                                    <th>每考场监考员数</th>
                                    <th>备用考场数</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($existing_data as $session): ?>
                                <tr>
                                    <td><?php echo $session['session_number']; ?></td>
                                    <td><?php echo htmlspecialchars($session['subject_name']); ?></td>
                                    <td><?php echo $session['exam_date']; ?></td>
                                    <td><?php echo $session['start_time']; ?></td>
                                    <td><?php echo $session['end_time']; ?></td>
                                    <td><?php echo htmlspecialchars($session['room_type']); ?></td>
                                    <td><?php echo $session['rooms_needed_without_backup']; ?></td>
                                    <td><?php echo $session['students_per_room']; ?></td>
                                    <td><?php echo $session['invigilators_per_room']; ?></td>
                                    <td><?php echo $session['backup_rooms_count']; ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- 计算按钮 -->
            <div class="mb-4">
                <button type="button" class="btn btn-success btn-lg" onclick="calculateData()">计算考试项目需要的考场总数及考试项目需要监考员总数</button>
            </div>
            
            <!-- 计算结果展示区域 -->
            <div id="calculation-results" style="display: none;">
                <div class="card">
                    <div class="card-header">
                        <h5>计算结果</h5>
                    </div>
                    <div class="card-body">
                        <div id="results-content"></div>
                    </div>
                </div>
            </div>
            
            <!-- 下一步按钮 -->
            <div class="mt-4 mb-4">
                <a href="arrange_examination_rooms_milestone3.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary btn-lg">下一步：遴选课室</a>
            </div>
        <?php endif; ?>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function calculateData() {
            // 显示加载状态
            const button = event.target;
            const originalText = button.innerHTML;
            button.innerHTML = '计算中...';
            button.disabled = true;
            
            fetch('', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=calculate_data'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayCalculationResults(data.calculations);
                } else {
                    alert('计算失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('计算过程中发生错误');
            })
            .finally(() => {
                button.innerHTML = originalText;
                button.disabled = false;
            });
        }
        
        function displayCalculationResults(calculations) {
            let html = '';
            
            // 1. 考试项目需要的考场总数（不含备用考场）
            html += '<div class="calculation-result">';
            html += '<h6>1. 考试项目需要的考场总数（不含备用考场）</h6>';
            html += '<p class="mb-0">通过遍历所有场次的考场需求，最大值为：<strong>' + calculations.project_total_rooms + '</strong> 个考场</p>';
            html += '</div>';
            
            // 2. 每场次需要监考员总数（不含备用考场）
            html += '<div class="calculation-result">';
            html += '<h6>2. 每场次需要监考员总数（不含备用考场）</h6>';
            calculations.session_invigilator_counts.forEach((count, index) => {
                html += '<div class="session-detail">第' + (index + 1) + '场次：<strong>' + count + '</strong> 名监考员</div>';
            });
            html += '</div>';
            
            // 3. 考试项目需要监考员总数（含备用考场）
            html += '<div class="calculation-result">';
            html += '<h6>3. 考试项目需要监考员总数（含备用考场）</h6>';
            html += '<p class="mb-0">所有场次监考员需求的最大值 + 备用考场监考员：<strong>' + calculations.project_total_invigilators + '</strong> 名监考员</p>';
            html += '</div>';
            
            document.getElementById('results-content').innerHTML = html;
            document.getElementById('calculation-results').style.display = 'block';
            
            // 滚动到结果区域
            document.getElementById('calculation-results').scrollIntoView({ behavior: 'smooth' });
        }
    </script>
</body>
</html>